package com.xy.tianyu.module.picture.fragment

import android.view.View
import androidx.lifecycle.rxLifeScope
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.xy.tianyu.LazyLoadBaseFragment
import com.xy.tianyu.R
import com.xy.tianyu.module.picture.activity.PicSearchActivity
import com.xy.tianyu.module.picture.adapter.PicCategoryHotAdapter
import com.xy.tianyu.module.picture.bean.SearchDayBean
import com.xy.tianyu.module.picture.bean.SearchDayItem
import com.xy.tianyu.network.Api
import kotlinx.android.synthetic.main.fragment_pic_category_hot.*
import rxhttp.RxHttp
import rxhttp.toClass

/**
 * @time 2020/10/13 11:04
 * @class 描述:
 */
class PicCategoryHotFragment: LazyLoadBaseFragment() {
    private var pageIndex = 0
    private val picHotList = mutableListOf<SearchDayItem>()
    private lateinit var picHotAdapter:PicCategoryHotAdapter
    override fun setContentView(): Int {
        return R.layout.fragment_pic_category_hot
    }

    override fun lazyLoad() {
        ry_pic_cate_hot.layoutManager = GridLayoutManager(activity,2)

        picHotAdapter = PicCategoryHotAdapter(R.layout.item_pic_cate_one,picHotList)
        ry_pic_cate_hot.adapter = picHotAdapter
        picHotAdapter.setOnItemClickListener(object :OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                PicSearchActivity.actionStart(activity!!,picHotList[position].search_word)
            }

        })
        request(true)
        refresh_pic_cate_hot.setOnRefreshListener {
            pageIndex = 0
            request(true)
        }

        refresh_pic_cate_hot.setOnLoadMoreListener {
            pageIndex++
            request(false)
        }
    }

    override fun stopLoad() {

    }

    private fun request(isRefresh:Boolean){
       rxLifeScope.launch({
           val searchDayBean = getCateHotData()
           val list = searchDayBean.items
           if (!list.isNullOrEmpty()){
               if (isRefresh){
                   picHotList.clear()
               }
               picHotList.addAll(list)
           }
           picHotAdapter.notifyDataSetChanged()
       },{
           ToastUtils.showShort(it.message)
       },{},{
           refresh_pic_cate_hot.finishRefresh()
           refresh_pic_cate_hot.finishLoadMore()
       })
    }
    private suspend fun getCateHotData(): SearchDayBean {
        return RxHttp.get(Api.DAY_DAY_SEARCH_PICTURE_BASE_URL+Api.DAY_DAY_SEARCH_PICTURE_CATEGORY_HOT_URL+pageIndex)
            .toClass<SearchDayBean>()
            .await()
    }
}